package engine.logic
{
	import engine.pool.IResoule;
	import engine.scene.player.BasePlayerModel;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Point;
	
	import newx.com.ResManager;
	
	/**
	 * 雪人逻辑 
	 * @author gf
	 * 
	 */	
	
	public class SnowBall extends MovieClip implements IResoule
	{
		private var _target:DisplayObject;
		private var _speed:int	 = 10;
		private var omega:Number = 10;
		private var _endCatchFunc:Function;
		private var snowBall:MovieClip;
		
		public function SnowBall()
		{
			super();
			snowBall	=	ResManager.newResClass("CustomControl_085") as MovieClip;
			addChild(snowBall);
		}

		public function set speed(value:int):void
		{
			_speed = value;
		}
		
		public function get Ball():MovieClip
		{
			return snowBall;
		}

		public function reset():void
		{
			removeEventListener(Event.ENTER_FRAME,catchMove);
			snowBall.stop();
		}
		
		public function get target():DisplayObject
		{
			return _target;
		}

		public function set target(value:DisplayObject):void
		{
			_target = value;
		}
		
		public function startCatch():void
		{
			if(target)
			{
				addEventListener(Event.ENTER_FRAME,catchMove);
			}
		}
		
		public function playEffect(val:String):void
		{
			try
			{
				snowBall.gotoAndPlay(val);
			}
			catch(e:Error){};
		}
		
		public function set endCatchFunc(func:Function):void
		{
			_endCatchFunc	=	func;
		}
		
		private function catchMove(e:Event):void
		{
			var point:Point			=	new Point(target.x,target.y);
			var globalPoint:Point	=	target.parent.localToGlobal(point);
			var dx:Number 			= x - globalPoint.x;
			var dy:Number 			= y - globalPoint.y;
			
			var angle:Number = (270 + 180*Math.atan2(dy,dx)/Math.PI)%360;
			
			var crtangle:Number = (angle - rotation )%360;
			
			var dir:Number = (crtangle <= 180)?1:-1;
			
			rotation = (crtangle<180 && crtangle > omega || crtangle > 180 && 360 - crtangle > omega)
				?(rotation + omega * dir):angle;
			
			x += _speed*Math.sin(rotation*Math.PI/180);
			
			y -= _speed*Math.cos(rotation*Math.PI/180);
			
			if((int(x) >= int(globalPoint.x - 20) || int(x) <= int(globalPoint.x + 20)) && (int(y) >= int(globalPoint.y - 20)||int(y) <= int(globalPoint.y + 20)))
			{
				removeEventListener(e.type,arguments.callee);
				_endCatchFunc.call();
				snowBall.stop();
			}
		}

	}
}